package com.shj.shiro.conf;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.shj.shiro.model.User;
import com.shj.shiro.service.UserService;
import com.shj.shiro.util.Encodes;

/**
 * 在Shiro中，认证和授权最终是通过Realm来获取应用程序中的用户、角色及权限信息的。
 * 
 * @author huangjian
 *
 */
public class AuthRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;


	/**
	 * 认证过程会交由Realm中的doGetAuthenticationInfo(token)方法
	 * token -- 包含了页面传进来的用户名和密码信息
	 * 
	 * 此方法主要对用户进行验证，不通过则抛出AuthenticationException
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken up = (UsernamePasswordToken) token;
		String username = up.getUsername();
		User user = userService.findByUserId(username);
		
		if(user == null){
			throw new UnknownAccountException("账号或密码不正确");
		}
		
		if(user.getStatus() == 0){
			throw new LockedAccountException("账号已被锁定,请联系管理员");
		}
		
		byte[] salt = Encodes.decodeHex(user.getPassword().substring(0,16));
		return new SimpleAuthenticationInfo(user, user.getPassword().substring(16), ByteSource.Util.bytes(salt), getName());
	}
	
	/**
	 * 对用户进行授权的方法
	 * 在此方法中，需要把用户的角色，权限等信息查询出来，并放入返回的AuthorizationInfo中
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}

}
